package com.iiitb.wtp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;

public class URLConnect {
	
	String tag = "";

	public String getTag() {
		return tag;
	}

	public void setTag(String tag) {
		this.tag = tag;
	}

	public URLConnect(Map<String, String> urlLinks) throws SQLException, ClassNotFoundException, IOException {

		Parser ObjParse = new Parser();
		Map<String, String> list = new HashMap<String, String>();
		//ArrayList<String> list = new ArrayList<String>();
		// for(int i=0; i<urlList.size(); i++){
		// Iterator iter = urlList.entrySet().iterator();
		for (int i = 0; i < Global.ITERATIONSTEPS; i++) {

			//for (Map.Entry<String, String> entry : urlList.entrySet()) {
			//for (String url : urlList) {
				
			System.out.println(i);
			
			for (Map.Entry<String, String> entry : urlLinks.entrySet()) {
				// while(iter.hasNext()){
				String url = entry.getKey();
				
				
				try {
					HttpHost proxy = new HttpHost("192.168.3.254", 8080, "http");
					HttpClient client = new DefaultHttpClient();
					client.getParams().setParameter(
							ConnRoutePNames.DEFAULT_PROXY, proxy);
					HttpGet get = new HttpGet(url);

					HttpResponse response = client.execute(get);
					InputStreamReader is = new InputStreamReader(response
							.getEntity().getContent(), "UTF8");
					BufferedReader rd = new BufferedReader(is);

					String line;
					String sourceLine = null;

					while ((line = rd.readLine()) != null) {
						sourceLine = sourceLine + line;
					}
					/*if (entry.getValue().equals("")) {
						setTag(ObjParse.parseTag(sourceLine));
					}*/
					// Call the parser from here
					//else {
					
					list.putAll(ObjParse.parse(sourceLine, url, entry.getValue()));
						//list.addAll(ObjParse.parse(sourceLine, url, tag, urlList));
						// urlList.putAll(list);
					//}

					rd.close();

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			urlLinks.clear();
			urlLinks.putAll(list);
		}
		//ObjParse.serialiseWG();
		ObjParse.calcProb();
		//ObjParse.runMarkovChain();
		//ObjParse.deserialiseWG();
		
	}
}